import React, { useState } from "react";
import { useHistory } from "react-router";
import './Login.scss';
import $axios from 'utils/request';


function Login(props) {
  let history = useHistory();
  let [user,setUser] = useState({
    phone: '13800000000',
    smsCode: '1234'
  });
  const onChange = (event)=>{
    let target = event.target;
    let name = target.name;
    let value = target.value;
    setUser({
      ...user,
      [name]:value
    })
  }
  const getCode = ()=> {
    $axios.post('/user/getSmsCode',{phone:user.phone}).then(res=> {
      console.log(res);
      setUser({
        ...user,
        smsCode: res.result.smsCode
      })
    })
  }
  const login = ()=> {
    $axios.post('/user/loginBySmsCode',user).then(res=> {
      console.log(res);
      props.setPhone(user.phone);
      props.setToken(res.result.token);
      history.push('/my');
    })
  } 
  

  return (
    <div className="login-index">
      <div className="login-box bg-fff">
        <div className="phone-box flex aic rel">
          <input
            className="phone pl-10 f16 reset-input"
            type="text" 
            value={user.phone}
            onChange={onChange}
            placeholder="请输入手机号，验证或登录"
          />
        </div>
        <div className="prove-box flex aic rel">
          <input
            className="code f16 pl-10 reset-input"
            type="text"
            value={user.smsCode}
            onChange={onChange}
            placeholder="请输入验证码"
          />
          <button onClick={getCode} className="get-code fff abs">获 取 验 证 码</button>
        </div>
        <div className="user-control flex jc-sa">
          <button className="cancel control-button">取 消</button>
          <button onClick={login} className="login control-button on">登 录</button>
        </div>
      </div>
    </div>
  );
}

import { bindActionCreators } from "redux"; 
import { connect } from "react-redux";
import {setPhone,setToken} from 'redux/user'; 

// 将state映射到props里， 这样state里的状态就可以使用props.xx来读取
function mapStateToProps(state) { 
  return {
    // phone: state.phone,
    // token: state.token,
  };
}

function mapDispatchToProps(dispatch) {
  return {
    // 绑定action creator，使其可以生效
    setPhone: bindActionCreators(setPhone, dispatch),
    setToken: bindActionCreators(setToken, dispatch),
  };
}

// 使用connect吧普通组件变成高阶组件
export default connect(mapStateToProps, mapDispatchToProps)(Login);
